package com.vgooo.client.mobile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.Brand;
import com.vgooo.bean.ProdAbstract;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.HorizontalListView;
import com.vgooo.client.ui.SortAdapter;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.DensityUtil;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.UmengUtils;

public class MobileMainActivity extends VGActivity {

	private final static String className = "MobileMainActivity";

	private List<ProdAbstract> prodsInfo;// 热门推荐手机列表
	private Map<String, List<ProdAbstract>> prods = new HashMap<String, List<ProdAbstract>>();
	private MobileAdapter adapter;// 网格视图适配器
	private GridView mobileGView;// 网格视图
	private ScrollView scrollView;
	// private List<Brand> brands;// 所有的品牌信息
	// private TextView[] brandTV;// 显示品牌的控件
	private List<Brand> brands;// 品牌信息
	private View moreBrands;

	private HorizontalListView brandsList;// 品牌信息列表
	private SortAdapter brandAdapter;;// 品牌列表适配器

	private int currentBrand = 0;

	private final static String HOT_PROD = "推荐";

	private Context context = this;

	private static int bc = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		detailVeiw = inflater.inflate(R.layout.moblie_main, null);
		setContentView(detailVeiw);
		initView();
		addListener();
		// this.
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		// new DataSAsyncLoader(cparent).execute(null);
		init();
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// Log.i(className, "手机中心。。。") ;

		

		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);

		if (ViewLayout.viwStack==null ||ViewLayout.viwStack.isEmpty()) {
			if(ViewLayout.viwStack==null){
				ViewLayout.viwStack =new Stack<ViewLayout>();
			}
			ViewLayout.viwStack.push(new ViewLayout(true, "手机中心", ViewLayout.ID_TAG_MOBILE,
					ViewLayout.TAB_TAG_MOBILE,this));

		}

		if (!isFirst && (brands == null || brands.isEmpty())) {
			// new DataSAsyncLoader(cparent).execute(null);
			init();
		} else {
			isFirst = false;
		}
		bc = 1;
		// 设置导航栏背景色
		Main.setNavBackground(ViewLayout.ID_TAG_MOBILE);
		Main.back.setVisibility(View.GONE);
		
		

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		bc = 1 ;
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// DebugTools.log(className, "你按下了返回键。。。。");
			switch (bc) {
			case 0:
//				ViewLayout.setViewBack(this);
				Main.isFist = true ;
				ViewLayout.viwStack.clear();
				this.finish();
				Main.activity.finish();
				System.gc();
				break;

			case 1:
				if(ViewLayout.viwStack.size()==1){
					Toast.makeText(this, "再按一次退出!", Toast.LENGTH_SHORT).show();
					bc--;
				}else{
					super.onKeyDown(keyCode, event);
				}
				break;
			}
		}
		return true;
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		mobileGView = (GridView) findViewById(R.id.mobile_main_gridView);

		scrollView = (ScrollView) findViewById(R.id.mobile_main_gridView_scrollview);

		brandsList = (HorizontalListView) findViewById(R.id.mobile_main_brands);

		moreBrands = findViewById(R.id.mobile_main_brands_sort_more);

	}

	@Override
	public void setupView() {
		log("brands = " + brands);
		brandAdapter = new SortAdapter(brands, R.layout.brand_item,
				R.id.brand_tv, moreBrands, context);
		brandsList.setAdapter(brandAdapter);

		// TODO Auto-generated method stub
		adapter = new MobileAdapter(prodsInfo, this);
		mobileGView.setAdapter(adapter);

		 new DownLaodData().execute("");
		
		
	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
		// 产品列表单击事件
		mobileGView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// TODO Auto-generated method stub
				ProdAbstract prod = (ProdAbstract) adapter.getItem(position);
				if (prod.isBlank) {
					return;
				}

				log("prod = " + prod);
//				StringBuffer link = new StringBuffer("proddetail?");
				StringBuffer link = new StringBuffer("proddetail2?");
				link.append("b=").append(prod.brand_html).append("&p=")
						.append(prod.prod_html).append("&sw=")
						.append("" + DensityUtil.dip2px(context, 320));
				log("link = " + link);
				Main.moblieDetailIntent.putExtra("link", link.toString());
//				Main.moblieDetailIntent.putExtra("pid", prod.prod_html);
				ViewLayout.setViewPre(true, "手机详情",
						ViewLayout.TAB_TAG_MOBILE_DETAIL,cparent);
			}
		});

		brandsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> v, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Brand brand = (Brand) brandAdapter.getItem(position);
				// brandAdapter.notifyDataSetChanged() ;
				// brandAdapter.tvs.get(position).setBackgroundResource(R.drawable.sort_text_select_bg);
				int len = brandAdapter.tvs.size();
				for (int i = 0; i < len; i++) {
					if (i == position) {
						brandAdapter.tvs.get(i).setBackgroundResource(
								R.drawable.sort_text_select_bg);
					} else {
						brandAdapter.tvs.get(i).setBackgroundResource(0);
					}
				}

				log("brand_id = " + brand.brand_id + "   brand_name = "
						+ brand.brand_name);
				new BrandDataChanage(brand).execute("");
			}
		});
	}

	@Override
	public void flashView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getData() {
		// TODO Auto-generated method stub
		try {
			String urlPath = HttpUtils.BASE_URI + "hotprod";
			
			prodsInfo = getHotProd(urlPath);

			prods.put(HOT_PROD, prodsInfo);
			
			brands = getBranchs();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {

		default:
			log("doClick() : 未定义单击后触发的事件");
			break;
		}
	}

	public static ArrayList<Brand> getBranchs() throws Exception {
		String urlPath = HttpUtils.BASE_URI + "brands";
		String jsonString = HttpUtils.getJsonString(urlPath);
		// Map<String, Object> m = GSonTools.getObjectMaps(jsonString);
		List<Map<String, Object>> list = GSonTools.getMulObjectList(jsonString);
		ArrayList<Brand> brands = new ArrayList<Brand>();
		Brand b = new Brand();
		b.brand_name = HOT_PROD;
		b.brand_id = "";
		brands.add(b);
		for (Map<String, Object> map : list) {
			Brand brand = new Brand();
			brand.brand_id = (String) map.get("brand_id");
			brand.brand_name = (String) map.get("brand_name");
			brands.add(brand);
		}
		urlPath = null ;
		jsonString = null ;
		return brands;

	}

	public static List<ProdAbstract> getHotProd(String urlPath)
			throws Exception {
		String jsonString = HttpUtils.getJsonString(urlPath);

		List<Map<String, Object>> prods = GSonTools
				.getMulObjectList(jsonString);
		List<ProdAbstract> prodInfos = new ArrayList<ProdAbstract>();
		for (Map<String, Object> map : prods) {
			ProdAbstract prod = new ProdAbstract();
			prod.brand_name = (String) map.get("brand_name");
			prod.brand_html = (String) map.get("brand_html");
			prod.prod_thumbnail = (String) map.get("prod_thumbnail");
			prod.prod_html = (String) map.get("prod_html");
			prod.prod_name = (String) map.get("prod_name");
			Map<String, Object> price = (Map<String, Object>) map.get("price");
			prod.price_sell = (String) price.get("price_sell");
			prodInfos.add(prod);
			map = null ;
		}
		jsonString = null ;
		prods = null ;
		return prodInfos;

	}

	/**
	 * 打印调试信息
	 * 
	 * @param info
	 */
	private void log(String info) {
//		Log.i(this.getClass().getSimpleName(), info);
		DebugTools.log(className, info);
	}

	private class DownLaodData extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			for (Brand brand : brands) {
				List<ProdAbstract> prodsList = prods.get(brand.brand_name);
				if (prodsList == null || prodsList.isEmpty()) {
					String urlPath = HttpUtils.BASE_URI + "category?b="
							+ brand.brand_id;
					try {
						prodsList = MobileAdapter.getProds(urlPath);
						prods.put(brand.brand_name, prodsList);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						UmengUtils.onError(MobileMainActivity.this,
								e.toString());
					}
				}
			}
			System.gc();
			return null;
		}

	}
	
	
	private class BrandDataChanage extends AsyncTask<String, String, List<ProdAbstract> > {

		private Brand brand ; 
		
		public BrandDataChanage(Brand brand) {
			super();
			this.brand = brand;
		}

		@Override
		protected List<ProdAbstract> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<ProdAbstract> prodsList = prods.get(brand.brand_name);
			if (prodsList == null || prodsList.isEmpty()) {
				String urlPath = HttpUtils.BASE_URI + "category?b="
						+ brand.brand_id;
				
				try {
					
					prodsList = MobileAdapter.getProds(urlPath);
					prods.put(brand.brand_name, prodsList);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					UmengUtils.onError(MobileMainActivity.this,
							e.toString());
				}finally{
					urlPath = null ;
					prodsList = null ;
				}
			}
			return prodsList;
		}
		
		protected void onPostExecute(List<ProdAbstract> result) {
			// TODO Auto-generated method stub
			if(result!=null&&!result.isEmpty()){
				scrollView.scrollTo(0, -scrollView.getMeasuredHeight());
				adapter.dataChanage(result);
				//清除软引用中图片缓存缓存
				BitmapUtils.cleanCache();
			}
			new DownLaodData().execute("");
			super.onPostExecute(result);
		}
		
	}

}
